﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using FlyHorse.LIMS.Model;
using FlyHorse.LIMS.WinApp.Utils;
using DevExpress.XtraCharts;
using FlyHorse.LIMS.WinApp.LanguageResource;

namespace FlyHorse.LIMS.WinApp.DataAnalyzeFroms.CurveForms
{
    public partial class CurveMainForm : DevExpress.XtraEditors.XtraForm
    {
        BLL.TestItemBll testItemBll = new BLL.TestItemBll();
        BLL.GoodBll goodsBll = new BLL.GoodBll();
        BLL.ToolBll toolBll = new BLL.ToolBll();
        BLL.ReportRawBll reportRawBll = new BLL.ReportRawBll();
        BLL.ReportSemiBll reportSemiBll = new BLL.ReportSemiBll();
        BLL.ReportMixBll reportMixBll = new BLL.ReportMixBll();
        BLL.ReportProductBll reportProductBll = new BLL.ReportProductBll();
        BLL.SysReportTypeBll reportTypeBll = new BLL.SysReportTypeBll();
        BLL.StandardRawBll standardRawBll = new BLL.StandardRawBll();
        BLL.StandardSemiBll standardSemiBll = new BLL.StandardSemiBll();
        BLL.StandardCustomerBll standardCustomerBll = new BLL.StandardCustomerBll();

        List<CurveData> CurveDataList = new List<CurveData>();
        public CurveMainForm()
        {
            InitializeComponent();
        }

        private void CurveMainForm_Load(object sender, EventArgs e)
        {
            //初始化数据类型
            comboBoxEdit_dataType.Properties.DataSource = toolBll.GetReportTyepList();

            //初始化样品名称
            var goodsList = goodsBll.LoadEntities(m => true).ToList();
            this.searchLookUpEdit_Goods.Properties.DataSource = goodsList;

            //初始化检验项目   checkedComboBoxEdit_TestItem
            var testItemList = testItemBll.LoadEntities(m => true).ToList();
            this.searchLookUpEdit_TestItem.Properties.DataSource = testItemList;

            //初始化取样位置
            var samplePlaceList = toolBll.GetSamplingPlaceList();
            this.lookUpEdit_samplePlace.Properties.DataSource = samplePlaceList;
            //初始化客户
            var customerList = toolBll.GetCustomerList();
            this.lookUpEdit_customer.Properties.DataSource = customerList;

        }

        private void simpleButton_search_Click(object sender, EventArgs e)
        {
            CurveDataList = null;
            if (comboBoxEdit_dataType.EditValue == null)
            {
                XtraMessageBox.Show(ResourceOverall.InputNull);
                return;
            }
            if (this.searchLookUpEdit_Goods.EditValue == null)
            {
                XtraMessageBox.Show(ResourceOverall.InputNull);
                return;
            }
            if (this.searchLookUpEdit_TestItem.EditValue == null)
            {
                XtraMessageBox.Show(ResourceOverall.InputNull);
                return;
            }

            string typeID = Convert.ToString(this.comboBoxEdit_dataType.EditValue);
            SysReportType reportType = reportTypeBll.LoadEntities(m => m.SysReportTypeID == typeID).First();
            string goodsID = Convert.ToString(searchLookUpEdit_Goods.EditValue);
            Good goods = goodsBll.LoadEntities(m => m.GoodsID == goodsID).First();
            string testItemID = Convert.ToString(this.searchLookUpEdit_TestItem.EditValue);
            TestItem testItem = testItemBll.LoadEntities(m => m.TestItemID == testItemID).First();
            List<CurveData> dataList = new List<CurveData>();


            #region      原材料检验报告
            if (reportType.SysReportTypeName == "原材料检验报告")
            {
                var reportRawMoldes = reportRawBll.LoadEntities(m => m.GoodsID == goodsID);
                if (this.dateEdit_startDate.EditValue != null)
                {
                    DateTime startDate = this.dateEdit_startDate.DateTime;
                    reportRawMoldes = reportRawMoldes.Where(m => m.SendDate >= startDate);
                }
                if (this.dateEdit_EndDate.EditValue != null)
                {
                    DateTime endDate = this.dateEdit_EndDate.DateTime;
                    reportRawMoldes = reportRawMoldes.Where(m => m.SendDate <= endDate);
                }
                reportRawMoldes = reportRawMoldes.OrderBy(m => m.SendDate);
                List<ReportRaw> reportRawList = reportRawMoldes.ToList();


                foreach (var reportRaw in reportRawList)
                {
                    foreach (var res in reportRaw.ReportRawResults)
                    {
                        if (res.ChineseName == testItem.ChineseName)
                        {
                            if (res.TestValue != null)
                            {
                                CurveData data = new CurveData();
                                data.DataTime = reportRaw.SendDate;
                                data.TestValue = Convert.ToDouble( res.TestValue);
                                dataList.Add(data);
                            }
                        }
                    }
                }
            }
            #endregion

            #region 过程检验报告
            else if (reportType.SysReportTypeName == "过程检验报告")
            {
                var reportSemiMoldes = reportSemiBll.LoadEntities(m => m.GoodsID == goodsID);
                if (this.dateEdit_startDate.EditValue != null)
                {
                    DateTime startDate = this.dateEdit_startDate.DateTime;
                    reportSemiMoldes = reportSemiMoldes.Where(m => m.SendDate >= startDate);
                }
                if (this.dateEdit_EndDate.EditValue != null)
                {
                    DateTime endDate = this.dateEdit_EndDate.DateTime;
                    reportSemiMoldes = reportSemiMoldes.Where(m => m.SendDate <= endDate);
                }
                if (lookUpEdit_samplePlace.EditValue!=null)
                {
                    string placeID = Convert.ToString(this.lookUpEdit_samplePlace.EditValue);
                    reportSemiMoldes = reportSemiMoldes.Where(m => m.SamplingPlaceID == placeID);
                }

                reportSemiMoldes = reportSemiMoldes.OrderBy(m => m.SendDate);
                List<ReportSemi> reportSemiList = reportSemiMoldes.ToList();
                foreach (var reportSemi in reportSemiList)
                {
                    foreach (var res in reportSemi.ReportSemiResults)
                    {
                        if (res.ChineseName == testItem.ChineseName)
                        {
                            if (res.TestValue != null)
                            {
                                CurveData data = new CurveData();
                                data.DataTime = reportSemi.SendDate;
                                data.TestValue = Convert.ToDouble( res.TestValue);
                                data.samplingPlace = reportSemi.SamplingPlace;
                                dataList.Add(data);
                            }
                        }
                    }
                }
            }
            #endregion

            #region 出厂检验报告
            else if (reportType.SysReportTypeName == "出厂检验报告")
            {
                var reportMixModels = reportProductBll.LoadEntities(m => m.GoodsID == goodsID);
                if (this.dateEdit_startDate.EditValue != null)
                {
                    DateTime startDate = this.dateEdit_startDate.DateTime;
                    reportMixModels = reportMixModels.Where(m => m.DateProduced >= startDate);
                }
                if (this.dateEdit_EndDate.EditValue != null)
                {
                    DateTime endDate = this.dateEdit_EndDate.DateTime;
                    reportMixModels = reportMixModels.Where(m => m.DateProduced <= endDate);
                }
                reportMixModels = reportMixModels.OrderBy(m => m.DateProduced);
                List<ReportProduct> reportMixList = reportMixModels.ToList();

                foreach (var reportSemi in reportMixList)
                {
                    foreach (var res in reportSemi.ReportProductResults)
                    {
                        if (res.ChineseName == testItem.ChineseName)
                        {
                            if (res.TestValue != null)
                            {
                                CurveData data = new CurveData();
                                data.DataTime = reportSemi.DateProduced;
                                data.TestValue =  Convert.ToDouble( res.TestValue);
                                data.customer = reportSemi.Customer;
                                dataList.Add(data);
                            }
                        }
                    }
                }
            }
            #endregion

            #region 废弃代码


            //#region  //原材料
            //if (comboBoxEdit_dataType.Text == "原材料检验报告")
            //{
            //    var reportRawMoldes = reportRawBll.LoadEntities(m => m.GoodsID == goodsID);
            //    if (this.dateEdit_startDate.EditValue != null)
            //    {
            //        DateTime startDate = this.dateEdit_startDate.DateTime;
            //        reportRawMoldes = reportRawMoldes.Where(m => m.SendDate >= startDate);
            //    }
            //    if (this.dateEdit_EndDate.EditValue != null)
            //    {
            //        DateTime endDate = this.dateEdit_EndDate.DateTime;
            //        reportRawMoldes = reportRawMoldes.Where(m => m.SendDate <= endDate);
            //    }
            //    reportRawMoldes = reportRawMoldes.OrderBy(m => m.SendDate);
            //    List<ReportRaw> reportRawList = reportRawMoldes.ToList();

            //    foreach (var reportRaw in reportRawList)
            //    {
            //        foreach (var res in reportRaw.ResultList)
            //        {
            //            if (res.ChineseName == testItem.ChineseName)
            //            {
            //                if (res.TestValue != null)
            //                {
            //                    CurveData data = new CurveData();
            //                    data.DataTime = reportRaw.SendDate;
            //                    data.TestValue = (double)res.TestValue;
            //                    dataList.Add(data);
            //                }
            //            }
            //        }
            //    }
            //}
            //#endregion
            //#region   //过程检验数据
            //if (comboBoxEdit_dataType.Text == "过程检验报告")
            //{
            //    var reportSemiMoldes = reportSemiBll.LoadEntities(m => m.GoodsID == goodsID);
            //    if (this.dateEdit_startDate.EditValue != null)
            //    {
            //        DateTime startDate = this.dateEdit_startDate.DateTime;
            //        reportSemiMoldes = reportSemiMoldes.Where(m => m.SendDate >= startDate);
            //    }
            //    if (this.dateEdit_EndDate.EditValue != null)
            //    {
            //        DateTime endDate = this.dateEdit_EndDate.DateTime;
            //        reportSemiMoldes = reportSemiMoldes.Where(m => m.SendDate <= endDate);
            //    }
            //    reportSemiMoldes = reportSemiMoldes.OrderBy(m => m.SendDate);
            //    List<ReportSemi> reportSemiList = reportSemiMoldes.ToList();

            //    foreach (var reportSemi in reportSemiList)
            //    {
            //        foreach (var res in reportSemi.ResultList)
            //        {
            //            if (res.ChineseName == testItem.ChineseName)
            //            {
            //                if (res.TestValue != null)
            //                {
            //                    CurveData data = new CurveData();
            //                    data.DataTime = reportSemi.SendDate;
            //                    data.TestValue = (double)res.TestValue;
            //                    dataList.Add(data);
            //                }
            //            }
            //        }
            //    }
            //}
            //#endregion
            //#region   //混合样
            //if (comboBoxEdit_dataType.Text == "合成样检验数据")
            //{
            //    var reportMixModels = reportMixBll.LoadEntities(m => m.GoodsID == goodsID);
            //    if (this.dateEdit_startDate.EditValue != null)
            //    {
            //        DateTime startDate = this.dateEdit_startDate.DateTime;
            //        reportMixModels = reportMixModels.Where(m => m.SendDate >= startDate);
            //    }
            //    if (this.dateEdit_EndDate.EditValue != null)
            //    {
            //        DateTime endDate = this.dateEdit_EndDate.DateTime;
            //        reportMixModels = reportMixModels.Where(m => m.SendDate <= endDate);
            //    }
            //    reportMixModels = reportMixModels.OrderBy(m => m.SendDate);
            //    List<ReportMix> reportMixList = reportMixModels.ToList();

            //    foreach (var reportSemi in reportMixList)
            //    {
            //        foreach (var res in reportSemi.ResultList)
            //        {
            //            if (res.ChineseName == testItem.ChineseName)
            //            {
            //                if (res.TestValue != null)
            //                {
            //                    CurveData data = new CurveData();
            //                    data.DataTime = reportSemi.SendDate;
            //                    data.TestValue = (double)res.TestValue;
            //                    dataList.Add(data);
            //                }
            //            }
            //        }
            //    }
            //}
            //#endregion
            //#region   //出厂
            //if (comboBoxEdit_dataType.Text == "出厂检验报告")
            //{
            //    var reportMixModels = reportProductBll.LoadEntities(m => m.GoodsID == goodsID);
            //    if (this.dateEdit_startDate.EditValue != null)
            //    {
            //        DateTime startDate = this.dateEdit_startDate.DateTime;
            //        reportMixModels = reportMixModels.Where(m => m.DateProduced >= startDate);
            //    }
            //    if (this.dateEdit_EndDate.EditValue != null)
            //    {
            //        DateTime endDate = this.dateEdit_EndDate.DateTime;
            //        reportMixModels = reportMixModels.Where(m => m.DateProduced <= endDate);
            //    }
            //    reportMixModels = reportMixModels.OrderBy(m => m.DateProduced);
            //    List<ReportProduct> reportMixList = reportMixModels.ToList();

            //    foreach (var reportSemi in reportMixList)
            //    {
            //        foreach (var res in reportSemi.ResultList)
            //        {
            //            if (res.ChineseName == testItem.ChineseName)
            //            {
            //                if (res.TestValue != null)
            //                {
            //                    CurveData data = new CurveData();
            //                    data.DataTime = reportSemi.DateProduced;
            //                    data.TestValue = (double)res.TestValue;
            //                    dataList.Add(data);
            //                }
            //            }
            //        }
            //    }
            //}
            //#endregion
            #endregion


            if (dataList.Count <= 0)
            {
                XtraMessageBox.Show(ResourceOverall.NoQuery);
                return;
            }
            CurveDataList = dataList;

            double? avgValue = null;
            double? midValue = null;
            double? rangeValue = null;
            double? allSigmaValue = null;
            double? sampSigmaValue = null;
            CalculateAvgMidRangeSigama(dataList, out avgValue, out midValue, out rangeValue, out allSigmaValue, out sampSigmaValue);

            this.barEditItem_avg.EditValue = avgValue;
            this.barEditItem_midValue.EditValue = midValue;
            this.barEditItem_QuanJu.EditValue = rangeValue;
            this.barEditItemZhongtiPianCha.EditValue = allSigmaValue;
            this.barEditItem_YangPinPianCha.EditValue = sampSigmaValue;


            // Bind the chart to the list.�
            ChartControl myChart = chartControl1;


       
           


            #region 显示滚动条

            #endregion


            myChart.DataSource = dataList;
            myChart.Series.Clear();
            // Create a series, and add it to the chart.�
            Series series1 = new Series(testItem.ChineseName, ViewType.Line);  //testItem
            series1.ArgumentScaleType = ScaleType.DateTime;
            series1.ValueScaleType = ScaleType.Numerical;

            myChart.Series.Add(series1);

            // Adjust the series data members.�
            series1.ArgumentDataMember = "DataTime";
            series1.ValueDataMembers.AddRange(new string[] { "TestValue" });


            if (chartControl1.Diagram != null)
            {
                XYDiagram diagram = (XYDiagram)chartControl1.Diagram;

                // Enable the diagram's scrolling.
                diagram.EnableAxisXScrolling = true;
                diagram.EnableAxisYScrolling = true;

                // Define the whole range for the X-axis. 
                //diagram.AxisX.WholeRange.Auto = false;
                //diagram.AxisX.WholeRange.SetMinMaxValues("A", "D");
               
                // Disable the side margins 
                // (this has an effect only for certain view types).
                diagram.AxisX.VisualRange.AutoSideMargins = false;

                // Limit the visible range for the X-axis.
                //diagram.AxisX.VisualRange.Auto = false;
                //diagram.AxisX.VisualRange.SetMinMaxValues("B", "C");
                // Define the whole range for the Y-axis. 

                double minV = dataList.Min(m => m.TestValue);
                double maxV = dataList.Max(m => m.TestValue);
                diagram.AxisY.WholeRange.Auto = false;
                diagram.AxisY.WholeRange.SetMinMaxValues(minV, maxV);

                ScrollBarOptions scrollBarOptions = diagram.DefaultPane.ScrollBarOptions;

                scrollBarOptions.BackColor = Color.White;
                scrollBarOptions.BarColor = Color.Blue;
                scrollBarOptions.BorderColor = Color.Navy;
                scrollBarOptions.BarThickness = 15;
                scrollBarOptions.XAxisScrollBarAlignment = ScrollBarAlignment.Far;
                scrollBarOptions.XAxisScrollBarVisible = true;

            }
        }

        private void CalculateAvgMidRangeSigama(List<CurveData> dataList, out double? avgValue, out double? midValue, out double? rangeValue, out double? allSigmaValue, out double? sampSigmaValue)
        {
            double sum = 0;
            foreach (var data in dataList)
            {
                sum = sum + data.TestValue;
            }
            avgValue = sum / dataList.Count;  //平均值
            dataList = dataList.OrderBy(m => m.TestValue).ToList();
            //中位数
            dataList = dataList.OrderBy(m => m.TestValue).ToList();
            if (dataList.Count % 2 == 0)  //偶数
            {
                int index1 = dataList.Count / 2;
                int index2 = index1 + 1;
                midValue = (dataList[index1 - 1].TestValue + dataList[index2 - 1].TestValue) / 2;
            }
            else     //奇数
            {
                int index1 = (int)Math.Ceiling((double)dataList.Count / 2);
                midValue = dataList[index1 - 1].TestValue;
            }
            rangeValue = dataList[dataList.Count - 1].TestValue - dataList[0].TestValue;  //全距

            //标准差
            //求和 
            double avg = (double)avgValue;
            double[] arr = new double[dataList.Count];
            for (int i = 0; i < dataList.Count; i++)
            {
                arr[i] = Math.Pow(dataList[i].TestValue - avg, 2);
            }
            double sumTemp = 0;
            foreach (var item in arr)
            {
                sumTemp = sumTemp + item;
            }
            double chuN = sumTemp / dataList.Count;
            double chuN1 = sumTemp / dataList.Count - 1;

            allSigmaValue = Math.Sqrt(chuN);  //总体标准偏差
            sampSigmaValue = Math.Sqrt(chuN1);
        }
        private void CalculateCaCpCpk(double? minValue, double? maxValue, double allSigma, double avg, double midValue, out double? cp, out double? ca, out double? cpk)
        {
            if (minValue != null && maxValue != null)
            {
                double T = (double)maxValue - (double)minValue;
                cp = T / (6 * allSigma);
                ca = (avg - midValue) / (T / 2);
            }
            else
            {
                cp = null;
                ca = null;
            }
            //cpk

            //最大值最小值都有
            if (minValue != null && maxValue != null)
            {
                double minVal = (double)minValue;
                double maxVal = (double)maxValue;

                double cpu = System.Math.Abs(maxVal - avg) / 3 * allSigma;     //最大值减去平均值 除以 3 sigma
                double cpl = System.Math.Abs(minVal - avg) / 3 * allSigma;
                cpk = cpu <= cpl ? cpu : cpl;
            }
            else if (minValue != null && maxValue == null)   //只有最小值
            {
                double minVal = (double)minValue;
                double cpl = System.Math.Abs(minVal - avg) / 3 * allSigma;
                cpk = cpl;
            }
            else if (minValue == null && maxValue != null)
            {
                double maxVal = (double)maxValue;
                double cpu = System.Math.Abs(maxVal - avg) / 3 * allSigma;
                cpk = cpu;
            }
            else    //最小值 最大值都没有   无法计算cpk
            {
                cpk = null;
            }
        }

        private void barButtonItem_exportExcel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (CurveDataList != null && CurveDataList.Count > 0)
            {
                ExportExcel(CurveDataList);
            }
            else
            {
                XtraMessageBox.Show(ResourceOverall.NoQuery);
                return;
            }

        }

        private void ExportExcel(List<CurveData> dataList)
        {
            //ExportExcelForm form = new ExportExcelForm(dataList);
            //form.ShowDialog();
        }


        //private List<CurveData> CalStatistics(List<CurveData> dataList, SysReportType reportType, Goods goods, TestItem testItem)
        //{
        //    StandardRaw standardRaw = standardRawBll.LoadEntities(m => m.GoodsID == goods.GoodsID && m.TestItemID == testItem.TestItemID).First();
        //    #region 统计数据
        //    //平均值
        //    double sum = 0;
        //    double avg = 0;
        //    double midValue = 0;
        //    foreach (var data in dataList)
        //    {
        //        sum = sum + data.TestValue;
        //    }
        //    avg = sum / dataList.Count;
        //    //中位数
        //    dataList = dataList.OrderBy(m => m.TestValue).ToList();
        //    if (dataList.Count % 2 == 0)  //偶数
        //    {
        //        int index1 = dataList.Count / 2;
        //        int index2 = index1 + 1;
        //        midValue = (dataList[index1 - 1].TestValue + dataList[index2 - 1].TestValue) / 2;
        //    }
        //    else     //奇数
        //    {
        //        int index1 = (int)Math.Ceiling((double)dataList.Count / 2);
        //        midValue = dataList[index1 - 1].TestValue;
        //    }
        //    //全距
        //    double r = dataList[dataList.Count - 1].TestValue - dataList[0].TestValue;
        //    //标准差
        //    //求和 
        //    double[] arr = new double[dataList.Count];
        //    for (int i = 0; i < dataList.Count; i++)
        //    {
        //        arr[i] = dataList[i].TestValue - avg;
        //    }
        //    double sumTemp = 0;
        //    foreach (var item in arr)
        //    {
        //        sumTemp = sumTemp + item;
        //    }
        //    double chuN = sumTemp / dataList.Count;
        //    double chuN1 = sumTemp / dataList.Count - 1;

        //    double allSigma = Math.Sqrt(chuN);  //总体标准偏差
        //    double samSigma = Math.Sqrt(chuN1);

        //    //cp  精确度   规格公差除以6sigma    ca 准确度    (平均值-标准中值)/(最大值减最小值)除以2
        //    Double? ca = new Double();
        //    Double? cp = new Double();
        //    if (standardRaw.MinValue != null && standardRaw.MaxValue != null)
        //    {
        //        double T = (double)standardRaw.MaxValue - (double)standardRaw.MinValue;
        //        cp = T / (6 * allSigma);
        //        ca = (avg - midValue) / (T / 2);
        //    }
        //    else
        //    {
        //        cp = null;
        //        ca = null;
        //    }

        //    //cpk
        //    Double? cpk = new Double();
        //    //最大值最小值都有
        //    if (standardRaw.MinValue != null && standardRaw.MaxValue != null)
        //    {
        //        double minValue = (double)standardRaw.MinValue;
        //        double maxValue = (double)standardRaw.MaxValue;
        //        double cpu = System.Math.Abs(maxValue - avg) / 3 * allSigma;     //最大值减去平均值 除以 3 sigma
        //        double cpl = System.Math.Abs(minValue - avg) / 3 * allSigma;
        //        cpk = cpu <= cpl ? cpu : cpl;
        //    }
        //    else if (standardRaw.MinValue != null && standardRaw.MaxValue == null)   //只有最小值
        //    {
        //        double minValue = (double)standardRaw.MinValue;
        //        double cpl = System.Math.Abs(minValue - avg) / 3 * allSigma;
        //        cpk = cpl;
        //    }
        //    else if (standardRaw.MinValue == null && standardRaw.MaxValue != null)
        //    {
        //        double maxValue = (double)standardRaw.MaxValue;
        //        double cpu = System.Math.Abs(maxValue - avg) / 3 * allSigma;
        //        cpk = cpu;
        //    }
        //    else    //最小值 最大值都没有   无法计算cpk
        //    {
        //        cpk = null;
        //    }

        //    this.barEditItem_avg.EditValue = avg;
        //    this.barEditItem_midValue.EditValue = midValue;
        //    this.barEditItem_QuanJu.EditValue = r;
        //    this.barEditItemZhongtiPianCha.EditValue = allSigma;
        //    this.barEditItem_YangPinPianCha.EditValue = samSigma;
        //    if (ca != null)
        //    {
        //        this.barEditItemZhunQueDu.EditValue = ca;
        //    }
        //    if (cp != null)
        //    {
        //        barEditItem_jingQueDu.EditValue = cp;
        //    }
        //    if (cpk != null)
        //    {
        //        barEditItemCPK.EditValue = cpk;
        //    }
        //    #endregion
        //    return dataList;
        //}
    }
}